package com.zhongc.advance.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 *                       
 * @Filename PermissionInterceptor.java
 *
 * @Description 
 *
 * @Version 1.0
 *
 * @Author zhongc
 *
 * @Email zhong_ch@foxmail.com
 *       
 * @History 
 *<li>Author: zhongc</li>
 *<li>Date: 2015年7月23日</li>
 *<li>Version: 1.0</li>
 *<li>Content: create</li>
 *
 */
public class PermissionInterceptor implements HandlerInterceptor {
	
	private final static PathMatcher matcher = new AntPathMatcher();
	/**
	 * 登录url
	 */
	private String loginurl;
	/**
	 * 无权限提示url
	 */
	private String nopermissionurl;
	

	public void setLoginurl(String loginurl) {
		this.loginurl = loginurl;
	}

	public void setNopermissionurl(String nopermissionurl) {
		this.nopermissionurl = nopermissionurl;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception e)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
//		HttpSession session = request.getSession();
//		User user = (User)session.getAttribute(Constant.Session.SESSION_USER_NAME);
//		if(user == null){
//			new RedirectHttpServletResponseWrapper(response).redirectByPost(loginurl, "_top", null);
//			return false;
//		}
//		List<String> permissions = (List<String>)session.getAttribute(Constant.Session.SESSION_PERMISSIONS_NAME);
//		if(permissions == null){
//			permissions = permissionQueryService.queryPermissionsByUserId(user.getUserId(), SourceSystem.BOSS).getPermissions();
//			session.setAttribute(Constant.Session.SESSION_PERMISSIONS_NAME, permissions);
//		}
//		if(check(request.getRequestURI(), permissions)){
//			return true;
//		}
//		new RedirectHttpServletResponseWrapper(response).redirectByPost(nopermissionurl, null, null);
		return true;
	}

	private static boolean check(String uri, List<String> permissions){
		if(permissions.size() < 1){
			return false;
		}
		for (String permission : permissions) {
			if(matcher.match(permission, uri)){
				return true;
			}
		}
		return false;
	}
}
